//
//  WXTimerHelper.m
//  打字效果
//
//  Created by tianlong on 2018/3/28.
//  Copyright © 2018年 tianlong. All rights reserved.
//

#import "WXTimerHelper.h"
#import <UIKit/UIKit.h>


@interface WXTimerHelper ()
@property (assign, nonatomic) SEL selector;
@property (assign, nonatomic) NSTimeInterval interval;
@property (strong, nonatomic) id target;
@property (strong, nonatomic) id userInfo;
@property (assign, nonatomic) BOOL repeats;
@property (assign, nonatomic) BOOL keepPause;
@property (strong, nonatomic) NSTimer *timer;
@end

@implementation WXTimerHelper

+ (instancetype)scheduledTimerWithTimeInterval:(NSTimeInterval)interval target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo{
    WXTimerHelper *helper = [[WXTimerHelper alloc] initWithTimeInterval:interval target:aTarget selector:aSelector userInfo:userInfo repeats:yesOrNo];
    return helper;
}

- (instancetype)initWithTimeInterval:(NSTimeInterval)interval target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo{
    self = [super init];
    if (self) {
        self.selector = aSelector;
        self.interval = interval;
        self.target = aTarget;
        self.userInfo = userInfo;
        self.repeats = yesOrNo;
        [self addNote];
    }
    return self;
}

#pragma mark - addNote
- (void)addNote{
    // 添加通知监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
}

- (void)removeNote{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillEnterForegroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - addTimer
- (void)resetTimer{
    self.timer = [NSTimer timerWithTimeInterval:self.interval target:self.target selector:self.selector userInfo:self.userInfo repeats:self.repeats];
    [self setTimerState:TimerStatePrepare];
}

#pragma mark - NoteCallBack
// 退到后台
- (void)willResignActive:(NSNotification *)note{
    if (self.timerState == TimerStateNone ||
        self.timerState == TimerStateInvalidate) {
        NSLog(@"timerStateName = %@",[self getTimerStateName:_timerState]);
        return;
    }
    
    if (self.timerState == TimerStatePause) {
        // 退到后台前就是暂停，再次进入前台保持暂停
        self.keepPause = YES;
        NSLog(@"timerStateName = %@",[self getTimerStateName:_timerState]);
        return;
    }
    
    [self pause];
}

// 回到前台
- (void)willEnterForeground:(NSNotification *)note{
    if (self.timerState == TimerStateInvalidate ||
        self.timerState == TimerStateInvalidate) {
        NSLog(@"timerStateName = %@",[self getTimerStateName:_timerState]);
        return;
    }
    
    if (self.keepPause) {// 保持暂停的重置标记
        self.keepPause = NO;
        NSLog(@"timerStateName = %@",[self getTimerStateName:_timerState]);
        return;
    }
    
    if(self.timerState == TimerStatePause && self.repeats){// 重复播放并且暂停，重启定时器
        [self resume];
    }
}

#pragma mark - 启动
- (void)resume {
    if (self.timerState == TimerStateRunning) {
        NSLog(@"timerStateName = %@",[self getTimerStateName:_timerState]);
        return;
    }
    
    if (self.timerState == TimerStateInvalidate ||
        self.timerState == TimerStateNone){
        [self resetTimer];
    }
    
    if (self.timerState == TimerStatePrepare) {
        [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    }
    
    if (self.timer != nil) {
        [self.timer setFireDate:[NSDate distantPast]];
        [self setTimerState:TimerStateRunning];
    }
}

#pragma mark - 暂停
- (void)pause {
    if (self.timerState == TimerStateInvalidate ||
        self.timerState == TimerStatePause ||
        self.timerState == TimerStatePrepare ||
        self.timerState == TimerStateNone) {
        NSLog(@"timerStateName = %@",[self getTimerStateName:_timerState]);
        return;
    }
    [self.timer setFireDate:[NSDate distantFuture]];
    [self setTimerState:TimerStatePause];
}


#pragma mark - 销毁
- (void)stop {
    [self setTimerState:TimerStateInvalidate];
    [self.timer invalidate];
    self.timer = nil;
}

#pragma mark - 设置定时器的状态
- (void)setTimerState:(TimerState)timerState{
    _timerState = timerState;
    if ([self.delegate respondsToSelector:@selector(timerHelper:timerState:)]) {
        [self.delegate timerHelper:self timerState:timerState];
    }
    NSLog(@"timerStateName = %@",[self getTimerStateName:_timerState]);
}

- (NSString *)getTimerStateName:(TimerState)timerState{
    NSString *timerStateName = @"";
    switch (timerState) {
        case TimerStateNone:
            timerStateName = @"TimerStateNone";
            break;
            
        case TimerStatePrepare:
            timerStateName = @"TimerStatePrepare";
            break;
            
        case TimerStateRunning:
            timerStateName = @"TimerStateRunning";
            break;
            
        case TimerStatePause:
            timerStateName = @"TimerStatePause";
            break;
            
        case TimerStateInvalidate:
            timerStateName = @"TimerStateInvalidate";
            break;
    }
    return timerStateName;
}

- (void)dealloc{
    [self stop];
    [self removeNote];
    NSLog(@"%s",__FUNCTION__);
}

@end
